#!/bin/sh

#
# Test various FAT file system operations at a large
# offset
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

# Check that we're not on a Raspberry Pi since this test doesn't work there.
case $HOST_ARCH in
    arm*)
        # Raspberry Pi and likely other 32-bit ARMs error out
	# on large files.
        exit 77
        ;;
    *)
        ;;
esac

# Skip this test on systems that don't support sparse files (check for
# at least 1 MB hole size support)
if ! $FWUP_CREATE --sparse-check "$WORK/sparse.bin" --sparse-check-size 0x100000; then
    echo "Skipping test since OS or filesystem lacks sparse file support"
    exit 77
fi

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 4300000000)
define(BOOT_PART_COUNT, 77238)

file-resource 1K.bin {
	host-path = "${TESTFILE_1K}"
}

task complete {
	on-init {
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
        on-resource 1K.bin {
                fat_write(\${BOOT_PART_OFFSET}, "1.bin")
        }
        on-finish {
                fat_cp(\${BOOT_PART_OFFSET}, "1.bin", "2.bin")
                fat_mv(\${BOOT_PART_OFFSET}, "2.bin", "3.bin")
        }
}
EOF

# Create the firmware file, then "burn it"
$FWUP_CREATE -c -f $CONFIG -o $FWFILE
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete

EXPECTED_OUTPUT=$WORK/expected.out
ACTUAL_OUTPUT=$WORK/actual.out

cat >$EXPECTED_OUTPUT << EOF
 Volume in drive : has no label
 Volume Serial Number is 0022-2DB6
Directory for ::/

1        bin      1024 1980-01-01   0:00
3        bin      1024 1980-01-01   0:00
        2 files               2 048 bytes
                         38 908 416 bytes free

EOF

# mtools doesn't seem to support large offsets, so move
# the FAT filesystem to a temp file for the checks
dd if=$WORK/fwup.img of=$WORK/fwup-fat.img skip=4300000000 2>/dev/null

# Check that the directory looks right
mdir -i $WORK/fwup-fat.img > $ACTUAL_OUTPUT
diff -w $EXPECTED_OUTPUT $ACTUAL_OUTPUT

# Check the contents of the file
for i in 1 3; do
    mcopy -n -i $WORK/fwup-fat.img ::/${i}.bin $WORK/actual.1K.bin
    cmp $TESTFILE_1K $WORK/actual.1K.bin
done

# Check the FAT file format using fsck
$FSCK_FAT $WORK/fwup-fat.img

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
